package com.lry.util.requestcore.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.MysqlType;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * @author ALI
 * @since 2023/5/16
 */
public class DbUtil {

    public static void createTable(JdbcTemplate jdbcTemplate, String idField, String targetTable, JSONArray saveList) {
        String sql = buildCreateSql(idField, targetTable, saveList);
        jdbcTemplate.execute(sql);
    }

    public static String buildCreateSql(String idField, String targetTable, JSONArray saveList) {
        Set<String> headers = new HashSet<>();
        int i = 0;
        for (Object o : saveList) {
            JSONObject stringObjectMap = (JSONObject) o;
            if (i == 10) {
                break;
            }
            i += 1;
            headers.addAll(stringObjectMap.keySet());
        }
        return buildCreateSql(headers, idField, targetTable);
    }

    public static String buildCreateSql(String idField, String targetTable, List<Map<String, Object>> saveList) {
        Set<String> headers = new HashSet<>();
        int i = 0;
        for (Map<String, Object> stringObjectMap : saveList) {
            if (i == 10) {
                break;
            }
            i += 1;
            headers.addAll(stringObjectMap.keySet());
        }
        return buildCreateSql(headers, idField, targetTable);
    }

    public static String buildCreateSql(Set<String> headerMap, String idField, String tableName) {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("CREATE TABLE `%s` (", tableName));
        List<String> tempField = new ArrayList<>();
        for (String s : headerMap) {
            if (s.equals(idField)) {
                continue;
            }
            String type = MysqlType.VARCHAR.getName();
            int lengthValue = 255;
            String primaryKey = "";
            tempField.add(String.format("`%s` %s%s %s", s, type, (String.format("(%d)", lengthValue)), primaryKey));
        }
        tempField.add(0, String.format("`%s` VARCHAR(64) PRIMARY KEY", idField));
        sb.append(String.join(",\r\n", tempField));
        sb.append(")");
        sb.append(";");
        return sb.toString();
    }
}
